var express = require('express');
var router = express.Router();
var data = require('../data/index.js')

let addressList=[
        { id: '1', name: '张三', tel: '13120563619', address: '湖南省邵阳市大祥区xxx路101号' },
        { id: '2', name: '王五', tel: '12313020120', address: '江苏省吴中区越溪街道' },
        { id: '3', name: '马六', tel: '12000000000', address: '浙江省杭州市拱墅区莫干山路 50 号' },
        { id: '4', name: '李七', tel: '15135620356', address: '湖南省长沙市天心区暮云街道' },
]
// 收获地址列表
router.get('/list', function (req, res, next) {
res.send(addressList)
    })
  

// 新增收获地址
router.post('/add', function (req, res, next) {

    let data = {
        id: addressList.length + 1,
        name: req.body.name,
        tel: req.body.tel,
        address: req.body.address
    }


    addressList.push(data)

    res.send({
        msg: '新增成功',
        code: 200,
        data: true
    })
})

router.get('/update', function (req, res, next) {
    if (!req.query.id) {
        res.send('缺少id字段')
        return
    }

    let index = addressList.findIndex(item => {
        return String(item.id) === String(req.query.id)
    })

    if(index < 0) {
        res.send({
            msg: '编辑失败',
            code: 500,
            data: false
        })

        return
    }

    addressList[index] = Object.assign({}, req.query)

    res.send({
        msg: '编辑成功',
        code: 200,
        data: true
    })
})

router.get('/delete', function (req, res, next) {
    if (!req.query.id) {
        res.send('缺少id字段')
    }

    let index = addressList.findIndex(item => {
        return String(item.id) === String(req.query.id)
    })

    if (index < 0) {
        res.send({
            msg: '删除失败',
            code: 500,
            data: false
        })
        return
    }

    addressList.splice(index, 1)

    res.send({
        msg: '删除成功',
        code: 200,
        data: true
    })
})
module.exports = router;